package com.xyzwps.mvckotlin.service

import com.alibaba.fastjson.JSONObject
import com.xyzwps.mvckotlin.config.WebProperties
import kotlinx.coroutines.reactive.awaitFirst
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono

@Service
class MarkdownItService(webProperties: WebProperties) {

    val client = WebClient.create(webProperties.service.jsonlyRoot)

    suspend fun render(content: String) = client.post().uri("/util/md")
            .contentType(MediaType.APPLICATION_JSON)
            .body(Mono.just(JSONObject(mapOf("content" to content))), JSONObject::class.java)
            .retrieve()
            .bodyToMono(MarkdownDto::class.java)
            .awaitFirst().renderedContent ?: ""
}

internal data class MarkdownDto(val renderedContent: String?)